package com.wuchao.xml;

import com.wuchao.entity.Bookstore;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author wuchao66
 * @Date 2023/9/9 10:18
 * @PackageName:com.wuchao.xml
 * @ClassName: Test
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
public class Test {//dom4j
    public static void main(String[] args) throws DocumentException, IOException {
        //你要导入dom4j读取类
        SAXReader reader = new SAXReader();
        //识别的你的文件-文档对象
        Document dom = reader.read("D:\\idea-project\\t163mybatis\\src\\main\\resources\\books.xml");
        //找到根节点
        Element gen = dom.getRootElement();
        //根节点新建子节点--层级关系，父亲加孩子
        Element t163 = gen.addElement("t163");
        t163.setAttributeValue("id","6");
        //子节点来加孙节点
        Element tt163 = t163.addElement("tt163");
        tt163.setText("我是新的孙节点");
        //删除节点
      //  t163.remove(tt163);
        //找到子节点
        Iterator iterator = gen.elementIterator();
        List<Bookstore> list=new ArrayList<>();
        //找子节点属性并循环遍历子节点的子节点
        while(iterator.hasNext()){
            Bookstore bookstore = new Bookstore();
            //遍历孩子
            Element zi = (Element)iterator.next();//zi=book
            System.out.println("子节点的名字"+zi.getName());
            //拿到子节点的属性
            List<Attribute> attributes = zi.attributes();
            attributes.forEach(xjj->{
                    System.out.println("子节点的属性名"+xjj.getName()
                            +"\t子节点的属性值"+xjj.getValue());
                    bookstore.book=Integer.parseInt(xjj.getValue());
            });
            //循环子节点的子节点
            Iterator sun = zi.elementIterator();
            while(sun.hasNext()){
                Element sunzi = (Element) sun.next();
                System.out.println(sunzi.getName()+"\t"
                        +sunzi.getStringValue());
                if(sunzi.getName().equals("name")){
                    bookstore.name=sunzi.getStringValue();
                }
            }
            list.add(bookstore);
        }
        list.forEach(System.out::println);
        //把改好的东西，放到一个新的文件里面，输出xml
        //curd
        XMLWriter writer = new XMLWriter(
                new FileWriter("D:\\idea-project\\t163mybatis\\src\\main\\resources\\newbooks.xml"));
        writer.write(dom);
        writer.close();
        System.out.println("新的写入完毕");
    }
}
